package com.ebelter.seneo.ui.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserinfos;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.LoginResponseSubInfo;
import com.ebelter.btcomlib.models.https.responses.RegisterResponse;
import com.ebelter.btcomlib.utils.MD5Utils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.VerifyUtils;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.activity_manager.ActivityManagers;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.seneo.R;
import com.ebelter.seneo.beans.httpresponse.AddChildrenRS;
import com.ebelter.seneo.contants.IUserContant;
import com.ebelter.seneo.models.SeneoNet;
import com.ebelter.seneo.ui.fragments.addinfos.AddInfo_Athlete_Fragment;
import com.ebelter.seneo.ui.fragments.addinfos.AddInfo_Birthday_Fragment;
import com.ebelter.seneo.ui.fragments.addinfos.AddInfo_Height_Fragment;
import com.ebelter.seneo.ui.fragments.addinfos.AddInfo_Name_Fragment;
import com.ebelter.seneo.ui.fragments.addinfos.AddInfo_Sex_Fragment;
import com.ebelter.seneo.ui.views.birthday.Birthday;
import com.ebelter.seneo.utils.SeneoUtils;

import static com.ebelter.seneo.ui.activitys.GuestSelectActivity.RESULT_CODE;
import static com.ebelter.seneo.ui.activitys.SeneoLoginActivity.saveUserDatas;

public class SeneoAddInfoActivity extends SeneoBaseActivity implements View.OnClickListener {



    public static final String TAG = "SeneoAddInfoActivity";


    public static final int CMD_addinfo = 2;
    public static final int CMD_register = 3;
    public static final int CMD_register_children = 4;//添加子用户命令


    public int currentCMD;
    private String topTitle;//注册子用户 传进来的名字
    private long userid;//注册子用户 传进来的主id或者增加用户信息的用户id
    public static void openSeneoAddInfoActivity(Activity activity,int requestCode,
                                                int cmd,String name,long userid){
        Intent intent=new Intent();
        intent.setClass(activity,SeneoAddInfoActivity.class);
        intent.putExtra("cmd",cmd);
        intent.putExtra("topTitle",name);
        intent.putExtra("userid",userid);
        activity.startActivityForResult(intent,requestCode);
    }


    RelativeLayout top_root_rl;

    ImageView top_iv;
    TextView top_tv1;

    TextView modify_psw_next_bt;


    private static final int F_ADD_HEIGHT=0;
    private static final int F_ADD_SEX=1;
    private static final int F_ADD_BIRTHDAY=2;
    private static final int F_ADD_ATHLETE=3;
    private static final int F_ADD_NAMEEMAILPSW=4;

    private int currentDisplayFragment;

    AddInfo_Height_Fragment mAddInfo_Height_Fragment;
    AddInfo_Sex_Fragment mAddInfo_Sex_Fragment;
    AddInfo_Birthday_Fragment mAddInfo_Birthday_Fragment;
    AddInfo_Athlete_Fragment mAddInfo_Athlete_Fragment;
    AddInfo_Name_Fragment mAddInfo_Name_Fragment;




    @Override
    protected int loadLayoutById() {
        return R.layout.activity_common2_ly;
    }
    @Override
    protected void initView() {
        // StatusBarUtil.setColor(this, Color.parseColor("#ff0000"));
       if (getIntent()!=null){
           currentCMD = getIntent().getIntExtra("cmd",0);
           if (currentCMD==0){
               throw new RuntimeException("参数不对劲");
           }
           topTitle = getIntent().getStringExtra("topTitle");
           userid = getIntent().getLongExtra("userid",-1);

           if (currentCMD==CMD_addinfo&&userid<0){
               throw new RuntimeException("参数不对劲");
           }
       }


        top_root_rl=findViewById(R.id.top_root_rl);
        top_root_rl.setBackgroundColor(0);

        top_iv=findViewById(R.id.top_iv);
        top_iv.setImageResource(R.drawable.ic_black_white);

        top_tv1=findViewById(R.id.top_tv1);
        ViewUtils.setTextViewStr(top_tv1,topTitle);
        ViewUtils.hideView(top_tv1);
        top_tv1.setTextColor(Color.parseColor("#FFFAFCFD"));

        modify_psw_next_bt=findViewById(R.id.modify_psw_next_bt);

        ViewUtils.displayView(top_iv);
      //  ViewUtils.displayView(top_tv1);

        top_iv.setOnClickListener(this);
        modify_psw_next_bt.setOnClickListener(this);
        //setNextBtEnabled(false);

        displayFragment(F_ADD_HEIGHT);
    }


    private void displayFragment(int whichFragment) {
        currentDisplayFragment=whichFragment;
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideAllFragment(transaction, mAddInfo_Height_Fragment,mAddInfo_Sex_Fragment,mAddInfo_Birthday_Fragment,mAddInfo_Athlete_Fragment,mAddInfo_Name_Fragment);//隐藏全部的fragment

        int contain = R.id.modifypsw_container;//容器
        ViewUtils.setTextViewStr(modify_psw_next_bt,"Next");
        if (whichFragment==F_ADD_HEIGHT){
            ViewUtils.displayView(modify_psw_next_bt);
            if (mAddInfo_Height_Fragment == null) {
                mAddInfo_Height_Fragment = new AddInfo_Height_Fragment();
                transaction.add(contain, mAddInfo_Height_Fragment);
            } else {
                transaction.show(mAddInfo_Height_Fragment);
            }

        }else if (whichFragment==F_ADD_SEX){
            ViewUtils.displayView(modify_psw_next_bt);
            if (mAddInfo_Sex_Fragment == null) {
                mAddInfo_Sex_Fragment = new AddInfo_Sex_Fragment();
                transaction.add(contain, mAddInfo_Sex_Fragment);
            } else {
                transaction.show(mAddInfo_Sex_Fragment);
            }

        } else if (whichFragment==F_ADD_BIRTHDAY){
            ViewUtils.displayView(modify_psw_next_bt);
            if (mAddInfo_Birthday_Fragment == null) {
                mAddInfo_Birthday_Fragment = new AddInfo_Birthday_Fragment();
                transaction.add(contain, mAddInfo_Birthday_Fragment);
            } else {
                transaction.show(mAddInfo_Birthday_Fragment);
            }

        }else if (whichFragment==F_ADD_ATHLETE){
            ViewUtils.displayView(modify_psw_next_bt);
            if (mAddInfo_Athlete_Fragment == null) {
                mAddInfo_Athlete_Fragment = new AddInfo_Athlete_Fragment();
                transaction.add(contain, mAddInfo_Athlete_Fragment);
            } else {
                transaction.show(mAddInfo_Athlete_Fragment);
            }
            ViewUtils.setTextViewStr(modify_psw_next_bt,"Done");
        }else if (whichFragment==F_ADD_NAMEEMAILPSW){
            if (mAddInfo_Name_Fragment == null) {
                mAddInfo_Name_Fragment = new AddInfo_Name_Fragment();
                transaction.add(contain, mAddInfo_Name_Fragment);
            } else {
                transaction.show(mAddInfo_Name_Fragment);
            }
            ViewUtils.goneView(modify_psw_next_bt);
        }

        currentDisplayFragment=whichFragment;
        transaction.commit();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_iv:
                back();
                break;
            case R.id.modify_psw_next_bt:
                next();
                break;
        }
    }

    private void next() {
        if (currentCMD==CMD_addinfo||currentCMD==CMD_register_children){
            //添加信息
            if (currentDisplayFragment!=F_ADD_ATHLETE){
                currentDisplayFragment++;
                displayFragment(currentDisplayFragment);
            }else {

                if (currentCMD==CMD_addinfo){
                    addChildrenInfoDone();
                }else {
                    registerChildrenDone();
                }

            }

        }else {
            //注册
            if (currentDisplayFragment!=F_ADD_NAMEEMAILPSW){
                currentDisplayFragment++;
                displayFragment(currentDisplayFragment);
                //主用户注册的在注册界面已经弄好了逻辑
            }

        }


    }


    //注册子用户
    private void registerChildrenDone() {
        if (System.currentTimeMillis()-lastClickTime<2000){
            LogUtils.i(TAG,"点击太快被屏蔽掉");
            return;
        }
        lastClickTime=System.currentTimeMillis();

        final String name=topTitle;
        final long mainId = userid;
        final int height = (int) mAddInfo_Height_Fragment.getHeight();
        final int sex = mAddInfo_Sex_Fragment.getSex();
        final Birthday birthday = mAddInfo_Birthday_Fragment.getBirthdayView();
        final int roleType = mAddInfo_Athlete_Fragment.getSelectedAthlete();//0是普通人1运动员

        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }

        LogUtils.i(TAG,"添加子用户信息：mainId="+mainId+"--name="+name+"--height="+height+"--sex="+sex+"--birthday="+birthday.getFatterDay()+"--roleType="+roleType);

        SeneoNet.getIntance().registerChildrenRequest(this,mainId,
                name, birthday.getFatterDay(),height,sex,roleType,
                1, new HttpResponse<AddChildrenRS>() {
                    @Override
                    public void result(boolean isRequestSuccess, String requestDes, AddChildrenRS addChildrenRS,String s) {

                        if (isRequestSuccess){
                            if (addChildrenRS.resultCode==0){
                                LogUtils.i(TAG,"添加子用户："+addChildrenRS);
                                ToastUtil.show(R.string.Registered_successfully);

                                saveChildrenUser(mainId,addChildrenRS.getResultData().getUserId(),name,
                                        height,sex,birthday.getFatterDay(),roleType);

                                Intent intent = new Intent();
                                intent.putExtra("SELECT_USERID",addChildrenRS.getResultData().getUserId());
                                setResult(RESULT_OK,intent);

                                finish();

                            }else {
                                ToastUtil.show(R.string.Registration_failed);
                            }
                        }else {
                            ToastUtil.show(R.string.Registration_failed);
                        }
                    }
                });




    }

    //保存一个子用户信息
    private void saveChildrenUser(long mainId, long userId, String name, int height, int sex, String fatterDay, int roleType) {
        SeneoUserinfos u=new SeneoUserinfos();
        u.host_id=mainId;
        u.user_id=userId;
        u.nickName=name;
        u.height=height;
        u.sex=sex;
        u.birthday=fatterDay;
        u.athlete=roleType;
        u.isHost=false;
        u.save();
        SeneoUtils.sendCommonEventBus(TAG,GuestSelectActivity.TAG+SeneoMembersListActivity.TAG, IUserContant.ICMDS.ADD_ONE_CHILDREN_USER_SUCCESS,"添加一个子用户成功");
    }


    private void addChildrenInfoDone() {
        int height = (int) mAddInfo_Height_Fragment.getHeight();
        int sex = mAddInfo_Sex_Fragment.getSex();
        Birthday birthday = mAddInfo_Birthday_Fragment.getBirthdayView();
        int selectedAthlete = mAddInfo_Athlete_Fragment.getSelectedAthlete();//0是普通人 1运动员
        addChildrenInfo(topTitle,height,sex,birthday,selectedAthlete);
    }


    private void back() {
        if (currentDisplayFragment==F_ADD_HEIGHT){
            finish();
        }else {
            currentDisplayFragment--;
            displayFragment(currentDisplayFragment);
        }
    }

    @Override
    public void onBackPressed() {
        back();
    }





    private long lastClickTime;
    private void addChildrenInfo(String name, int height, int sex, Birthday birthday, int selectedAthlete) {
        if (System.currentTimeMillis()-lastClickTime<2000){
            LogUtils.i(TAG,"点击太快被屏蔽掉");
            return;
        }
        lastClickTime=System.currentTimeMillis();
        LogUtils.i(TAG,"----addChildrenInfo name="+name+"--height="+height+"--sex="+sex+"---birthday="+birthday.getFatterDay()+"---selectedAthlete(0运动员1普通)="+selectedAthlete+"---userid="+userid);


    }



    //注册主用户
    public void startRegisterHostUser(final String name, String email, final String psw1, String psw2) {
        int height = (int) mAddInfo_Height_Fragment.getHeight();
        int sex = mAddInfo_Sex_Fragment.getSex();
        Birthday birthday = mAddInfo_Birthday_Fragment.getBirthdayView();
        int roleType = mAddInfo_Athlete_Fragment.getSelectedAthlete();//0是普通人1运动员

        if (TextUtils.isEmpty(name)){
            ToastUtil.show(R.string.Nikename_cannot_be_empty);
            return;
        }
        if (name.length()>20){
            ToastUtil.show(R.string.nikename_over_tip);
            return;
        }

        if (TextUtils.isEmpty(email)){
            ToastUtil.show(R.string.Email_must_not_be_empty);
            return;
        }


        if (!VerifyUtils.emailFormat(email)){
            ToastUtil.show(R.string.Incorrect_email_format);
            LogUtils.i(TAG,"注册的邮箱是 email = " + email+"---不符合邮箱格式");
           // ToastUtil.show("注册的邮箱是 email = " + email);
            return;
        }

        if (TextUtils.isEmpty(psw1)){
            ToastUtil.show(R.string.The_Password_cannot_be_empty);
            return;
        }

        if (psw1.length()<6){
            ToastUtil.show("Password contains at least 6 characters");
            return;
        }

        if (!TextUtils.equals(psw1,psw2)){
            ToastUtil.show(R.string.The_password_is_inconsistency_twice);//前后密码输入不一致
            return;
        }

        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        SeneoNet.getIntance().registerRequest(this,0,
                name, email, MD5Utils.getMd5(psw1),birthday.getFatterDay(),height,sex,roleType,
                1, new HttpResponse<RegisterResponse>() {
                    @Override
                    public void result(boolean isRequestSuccess, String requestDes, RegisterResponse registerResponse,String s) {

                        if (isRequestSuccess){
                            if (registerResponse.resultCode==0){
                                LogUtils.i(TAG,"注册返回："+registerResponse.resultMessage);
                                ToastUtil.show(R.string.Registered_successfully);
                                login(name,psw1);


                              //  startActivity(new Intent(SeneoAddInfoActivity.this,SeneoLoginActivity.class));
                                //finish();

                            }else if (registerResponse.resultCode==106){
                                ToastUtil.show(R.string.Email_verification_code_has_expired);
                            }else if (registerResponse.resultCode==107){
                                ToastUtil.show(R.string.Wrong_email_verification_code);
                            }else if (registerResponse.resultCode==103||registerResponse.resultCode==-1){
                                ToastUtil.show(R.string.The_email_or_nickname_has_been_registered);
                            } else if (registerResponse.resultCode==110){
                                ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                            } else {
                                ToastUtil.show(R.string.Registration_failed);
                            }
                        }else {
                            ToastUtil.show(R.string.Registration_failed);
                        }
                    }
                });





    }

    //登录
    private void login(final String name, final String psw) {
        SeneoNet.getIntance().loginRequest(this, false, name,MD5Utils.getMd5(psw) , new HttpResponse<LoginResponseSubInfo>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, LoginResponseSubInfo loginResponse,String s) {
                // dissLoadingDialog();
                LogUtils.i2(TAG,"----登录=loginResponse="+loginResponse);
                // {resultData=null, responseStr='null', resultCode=-1, resultMessage='不存在的email或者昵称'}
                if (isRequestSuccess){
                    if (loginResponse.resultCode==0){

                        UserSpUtil.writeString(IUserContant.IUser.loginName,name);
                        UserSpUtil.writeString(IUserContant.IUser.psw,MD5Utils.getMd5(psw));
                        UserSpUtil.writeString(IUserContant.IUser.psw2,psw);
                        //登录成功
                        saveUserDatas(loginResponse);
                        //ToastUtil.show("Login successfully!");
                        SeneoMainActivity.openSeneoMainActivity(SeneoAddInfoActivity.this,false);
                        ActivityManagers.getInstance().closeActivity(SeneoLoginActivity.TAG);//关闭登录界面
                        finish();
                    }else if (loginResponse.getResultCode()==109){//109是：不存在的email或者昵称
                        ToastUtil.show(R.string.mail_nickname_no_exist);
                    }else if(loginResponse.getResultCode()==111||loginResponse.getResultCode()==-1){//111密码错误
                        ToastUtil.show(R.string.psw_error);
                    }else if (loginResponse.getResultCode()==110){//服务器异常
                        ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                    }

                }else {
                    ToastUtil.show(R.string.Network_connection_error);
                }
            }
        });
    }


}
